package cn.com.sparkle.paxos.paxosinstance;

import java.util.Set;

import org.apache.log4j.Logger;

import com.google.protobuf.GeneratedMessage;

import cn.com.sparkle.paxos.ClusterState;
import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.ElectionId;
import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.ElectionPrepareRequest;
import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.ElectionSuccessMessage;
import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.ElectionVoteRequest;
import cn.com.sparkle.paxos.iomodel.protobuffmessage.PaxosMessages.Value;
//import cn.com.sparkle.paxos.model.ElectionId;
//import cn.com.sparkle.paxos.model.Id;
import cn.com.sparkle.paxos.net.NetNode;
//import cn.com.sparkle.paxos.net.message.PrepareRequest;
//import cn.com.sparkle.paxos.net.message.SuccessMessage;
//import cn.com.sparkle.paxos.net.message.VoteRequest;
//import cn.com.sparkle.paxos.net.message.election.ElectionPrepareRequest;
//import cn.com.sparkle.paxos.net.message.election.ElectionSuccessMessage;
//import cn.com.sparkle.paxos.net.message.election.ElectionVoteRequest;

public class ElectionPaxosInstance extends PaxosInstance {
	private final static Logger logger = Logger
			.getLogger(ElectionPaxosInstance.class);
	private ClusterState cState;
	private ElectionId id;

	public ElectionPaxosInstance(Set<NetNode> activeNode, int quorum,
			ElectionId id, ClusterState cState, String address) {
		super(activeNode, quorum, 0, address);
		this.cState = cState;
		this.id = id;
	}

	@Override
	public Value getWantAssginValue() {
		return Value.getDefaultInstance();
	}

	@Override
	public void voteSuccess(Value value) {
		cState.changeLastElectionId((ElectionId) id);
	}

	@Override
	public GeneratedMessage getSuccessMessage(Value lastValue) {
		ElectionSuccessMessage.Builder builder = ElectionSuccessMessage
				.newBuilder();
		builder.setId(id);
		return builder.build();
		// return new ElectionSuccessMessage((ElectionId) id);
	}

	@Override
	public GeneratedMessage getPrepareRequest() {
		ElectionPrepareRequest.Builder builder = ElectionPrepareRequest
				.newBuilder();
		builder.setId(id);
		return builder.build();
		// return new ElectionPrepareRequest((ElectionId) id);
	}

	@Override
	public GeneratedMessage getVoteRequest(Value lastValue) {
		ElectionVoteRequest.Builder builder = ElectionVoteRequest.newBuilder();
		builder.setId(id);
		return builder.build();
		// return new ElectionVoteRequest((ElectionId) id);
	}

	@Override
	public void instanceFail(long refuseId) {
		logger.debug("election refuseId " + refuseId);
		if (refuseId >= cState.getSelfState().getElectionVoteIdBySelf().getId()
				.getIncreaseId()) {
			cState.getSelfState().getElectionVoteIdBySelf().getIdBuilder()
					.setIncreaseId(refuseId + 1);
		}

	}

}
